package vn.vfriends.vbox.redis.service;

import java.util.Map;
import javax.ejb.Stateless;
import javax.inject.Inject;
import org.apache.commons.beanutils.BeanUtilsBean;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import vn.vfriends.vbox.model.Storage;

/**
 *
 * @author tuancn
 */
@Stateless
public class StorageRedis {
    
    public static final String STORAGE_KEY = "storage:%s";
    
    @Inject
    private Jedis jedis;
    
    public void addStorage(Integer accountId, Storage storage) throws Exception {
        Pipeline pipeline = jedis.pipelined();
        
        Map<String, String> properties = BeanUtilsBean.getInstance().describe(storage);
        pipeline.hmset(String.format(STORAGE_KEY, accountId), properties);
        
        pipeline.sync();
    }
    
    public Storage getStorage(Integer accountId) throws Exception {
        String storageKey = String.format(STORAGE_KEY, accountId);
        Map<String, String> properties = jedis.hgetAll(storageKey);
        
        if (properties == null || properties.isEmpty()) {
            return null;
        } else {
            Storage storage = new Storage();
            BeanUtilsBean.getInstance().populate(storage, properties);

            return storage;
        }
    }
}